<!-- 评分类制表 -->
<template>
  <div class="rateForm">
    <create-form-header ref="formHeader" :initial-form-data="initialFormData" :is-preview="isPreview" :disabled="disabled"></create-form-header>
    <form-tree ref="formTree"
      :is-preview="isPreview"
      :tree-data="treeData"
      :checkResult="checkResult"
      :attr="attributes"
    ></form-tree>
  </div>
</template>

<script>
import CreateFormHeader from '../../components/CreateFormHeader'
import previewApplyForm from '../../writeForm/rateForm/index.vue'
import formTree from './tree.vue'
import confirmApproval from '../applyForm/components/confirmApproval.vue'
import importModal from '../../components/importModal.vue'
import { mapState } from 'vuex'
import { findNodePath } from '@/views/menuList/menus'
import { checkTreeWeight } from './utils'
import { parseTreeData } from '../../writeForm/rateForm/utils'
import formCenterApi from '@/api/formCenter.js'
import { uuid } from 'vue-uuid'

export default {
  components: { CreateFormHeader, formTree },
  data() {
    return {
      baseInfo: {
        tip: '',
        tipFile: []
      },
      treeData: [],
      checkResult: null,
      attributes: {},
      timer: null
    }
  },
  props: {
    row: {
      type: Object,
      default: () => {}
    },
    isPreview: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    ...mapState(['menuList']),
    initialFormData() {
      return {
        name: this.row.name,
        menu: findNodePath(this.menuList, this.row.menu),
        remark: this.row.remark,
        tip: this.baseInfo.tip,
        tipFile: this.baseInfo.tipFile,
      }
    }
  },
  methods: {
    init() {
      const initAttr = {
        numberType: 0,
        scoreRequire: 1,
        type: 0,
        maxlength: 300,
        scoreDesReq: 0
      }
      if (this.row.config) {
        const config = JSON.parse(this.row.config)
        this.baseInfo = config.baseInfo
        if (this.row.name !== config.treeData[0].label) {
            config.treeData[0].label = this.row.name
          }
        this.treeData = config.treeData
        this.attributes = this.treeData[0].attributes || initAttr
      } else {
        this.treeData.push({
          id: uuid.v1(),
          label: this.row.name,
          weight: 100,
          class: 'first_node',
          tip: '',
          children: []
        })
        this.attributes = initAttr
      }
    },
    setPageActions() {
      const btnList = [
        {
          text: '一键导入',
          handle: this.importHandle
        },
        {
          text: '暂存',
          handle: this.saveTemp
        },
        {
          text: '预览',
          handle: this.handlePreview
        },
        {
          text: '取消',
          handle: () => {
            this.$emit('Close')
          }
        },
        {
          text: '提交',
          theme: 'primary',
          handle: this.submit
        }
      ]
      this.$emit('SetPageActions', btnList)
    },
    importHandle() {
      new this.$pageModal(
        importModal,
        {
          props: {
            formType: this.row.type
          }
        },
        data => {
          data && this.parseFileJson(data)
        }
      )
    },
    // 解析file的json转为树结构
    parseFileJson(rows) {
      try {
        let treeData = []
        let levelNodes = [null, ...Array(5).fill(null)]
         // 用于根据层级寻找或创建节点的函数
         const findOrCreateNode = (level, parentNode, label, tip, weight) => {
          if (!parentNode) return null
          let node = parentNode.children.find(child => child.label === label)
          if (!node) {
            node = { id: uuid.v1(), label, tip, weight, children: [] }
            parentNode.children.push(node)
          }
          levelNodes[level] = node // 更新当前层级的节点
          return node
         }
        rows.forEach(row => {
          const [level1, level1Tip, level1Weight, level2, level2Tip, level2Weight, level3, level3Tip, level3Weight, level4, level4Tip, level4Weight, level5, level5Tip, level5Weight] = row
          if (level1) {
            levelNodes[1] =
              levelNodes[1] && levelNodes[1].label === level1
                ? levelNodes[1]
                : { id: uuid.v1(), label: level1, tip: level1Tip, weight: level1Weight, children: [] }
            if (!treeData.some(node => node.id === levelNodes[1].id)) {
              treeData.push(levelNodes[1])
            }
          }
          if (level2) {
            levelNodes[2] = findOrCreateNode(2, levelNodes[1], level2, level2Tip, level2Weight)
          } else {
            levelNodes[2] = null // 重置level2节点，以确保不会错误地使用之前的节点
          }
          if (level3) {
            levelNodes[3] = findOrCreateNode(3, levelNodes[2] || levelNodes[1], level3, level3Tip, level3Weight)
          } else {
            levelNodes[3] = null // 重置level3节点
          }
          if (level4) {
            // 注意这里回退到level2，因为level3可能不存在
            levelNodes[4] = findOrCreateNode(4, levelNodes[3] || levelNodes[2] || levelNodes[1], level4, level4Tip, level4Weight)
          } else {
            levelNodes[4] = null // 重置level4节点
          }
          if (level5) {
            // 注意这里同样需要回退，因为level4或level3可能不存在
            levelNodes[5] = findOrCreateNode(
              5,
              levelNodes[4] || levelNodes[3] || levelNodes[2] || levelNodes[1],
              level5,
              level5Tip,
              level5Weight
            )
          }
        })
        this.treeData[0].children = treeData
        this.$nextTick(() => {
          this.$refs.formTree.selectFirstNode()
        })
      } catch (error) {
        console.log('error', error)
        this.$Message.error({
          content: '导入失败',
          duration: 2
        })
      }
    },
    saveTemp(auto) {
      // 权重不对时，找到对应节点的id
      // this.checkResult = checkTreeWeight(this.treeData[0], this.treeData[0].id)
      // if (this.checkResult) {
      //   this.$Message.error({
      //     content: '权重设置错误，请您修改',
      //     duration: 2
      //   })
      //   return
      // }
      this.treeData[0].attributes = this.$refs.formTree.attributes
      const config = {
        baseInfo: { tip: this.$refs.formHeader.formData.tip, tipFile: this.$refs.formHeader.formData.tipFile },
        treeData: this.treeData
      }
      const params = {
        id: this.row.id,
        name: this.row.name,
        type: this.row.type,
        year: this.row.year,
        remark: this.row.remark,
        // menu: this.createForm.menu[this.createForm.menu.length - 1],
        menu: this.row.menu,
        config: JSON.stringify(config)
      }
      formCenterApi.formSaveOrUpdate(params).then(res => {
        if (res.data.code === 200) {
          this.$Message.success({
            content: auto ? '自动暂存成功' : '暂存成功',
            duration: 2
          })
        } else {
          this.$Message.error({
            content: '暂存错误',
            duration: 2
          })
        }
      })
      this.$refs.formTree.isDirty = false
    },
    handlePreview() {
      new this.$sidelipPage(
        previewApplyForm,
        {
          props: {
            row: {
              treeData: this.$refs.formTree.treeData,
              baseInfo: { tip: this.$refs.formHeader.formData.tip, tipFile: this.$refs.formHeader.formData.tipFile },
            },
            rateTitle: this.row.name,
            isPreview: true,
            attrs: this.attributes
          }
        },
      )
    },
    cancel() {
      this.$emit('Close')
    },
    submit() {
      // 权重不对时，找到对应节点的id
      this.checkResult = checkTreeWeight(this.treeData[0], this.treeData[0].id)
      if (this.checkResult) {
        this.$Message.error({
          content: '权重设置错误，请您修改',
          duration: 2
        })
        return
      }
      const data = parseTreeData(this.treeData[0]).result
      const cell = parseTreeData(this.treeData[0]).cell
      // 迎合后端
      const fieldMap = {
        "bccb-b569197ef5ce": {
          id: 'bccb-b569197ef5ce',
          type: 20,
          label: '-',
          layout: 9,
          required: false,
          labelWidth: "170px",
          attrs: {
            data,
            cell
          }
        }
      }
      this.treeData[0].attributes = this.$refs.formTree.attributes
      const config = {
        baseInfo: { tip: this.$refs.formHeader.formData.tip, tipFile: this.$refs.formHeader.formData.tipFile },
        treeData: this.treeData,
        fieldMap,
      }
      const submitParams = {
        id: this.row.id,
        name: this.row.name,
        type: this.row.type,
        year: new Date().getFullYear(),
        remark: this.row.remark,
        // menu: this.createForm.menu[this.createForm.menu.length - 1],
        menu: this.row.menu,
        processId: this.row.processId,
        approverList: JSON.parse(this.row.config || '{}').approverList || [],
        isApprove: JSON.parse(this.row.config || '{}').isApprove,
        config: JSON.stringify(config)
      }
      new this.$pageModal(
        confirmApproval,
        {
          props: {
            submitParams: submitParams
          }
        },
        data => {
          data && this.$emit('Close', true)
          data &&
            this.$Message.success({
              content: '提交成功',
              duration: 2
            })
        }
      )
    }
  },
  created() {
    this.init()
    this.setPageActions()
    // 初始化树数据
    // this.initializeTreeData()
    this.$nextTick(() => {
      this.$refs.formTree?.selectFirstNode()
    })
  },
  mounted() {
    // 三分钟自动暂存一次
    this.timer = setInterval(() => {
      if (this.$refs.formTree.isDirty) {
        this.saveTemp(true)
      }
    }, 1000 * 60 * 3)
  },
  beforeDestroy() {
    clearInterval(this.timer)
  }
}
</script>

<style lang="less" scoped>
.rateForm {
  padding-left: 20px;
  padding-right: 20px;
  padding-top: 10px;
}
</style>